package com.tju.Controller.system;


import com.google.code.kaptcha.Constants;
import com.tju.IDao.CategoryMapper;
import com.tju.Model.User;
import com.tju.Util.JsonConverterUtil;
import com.tju.Util.MenuTree;
import com.tju.Util.ResultDO;
import com.tju.model.MenuObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.tju.Service.ResourcesService;
import com.tju.Service.UserRoleService;
import com.tju.Service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by search on 2016/11/16.
 */
@Slf4j
@Controller
@RequestMapping("/system")
public class UserLoginController {

    @Autowired
    private AuthenticationManager myAuthenticationManager;

    @Resource
    UserService userServiceImpl;

    @Resource
    UserRoleService userRoleServiceImpl;

    @Resource
    ResourcesService resourcesServiceImpl;

    @Autowired
    CategoryMapper categoryMapper;



    @RequestMapping(value="/login",method= RequestMethod.POST)
    @ResponseBody
    public String login(@RequestParam(defaultValue="") String username,
                      @RequestParam(defaultValue="") String password,
                      @RequestParam(defaultValue="") String verifyCode,
                      HttpServletRequest request)
    {

        HttpSession session = request.getSession();
        String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        //首先校验验证码
        if(!verifyCode.equals(code))
        {
            return JsonConverterUtil.loginInfoByJson("验证码输入错误，请重试！",false);
        }


        username = username.trim();
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        try {
            Authentication authentication = myAuthenticationManager.authenticate(authRequest); //调用loadUserByUsername
            SecurityContextHolder.getContext().setAuthentication(authentication);
            session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext()); // 这个非常重要，否则验证后将无法登陆
            session.setAttribute("loginUser", username);
            UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                    .getAuthentication()
                    .getPrincipal();
            User loginUser = this.userServiceImpl.selectLogin(userDetails.getUsername());
            session.setAttribute("loginId", loginUser.getUserId());
            session.setAttribute("loginUserEnity", loginUser);

            String menuTree = buildMenuTree(loginUser.getUserId());
            if(menuTree!=null)
            {
                session.setAttribute("isMenuCreateSuccess",true);
                session.setAttribute("myMenuList",menuTree);
            }else{
                session.setAttribute("isMenuCreateSuccess",false);
            }



           /* //设置用户菜单
            ResultDO<List<MenuObject>> listResultDO = userRoleServiceImpl.selectMenusByUserID(loginUser.getUserId());
            HashMap<Integer, String> categoryMap = getCategoryMap();
            LinkedHashMap<String, List<MenuObject>> finalMenuMap = new LinkedHashMap<>();
            if(listResultDO.isSuccess())
            {
                List<MenuObject> menuList = listResultDO.getModule();
                for(MenuObject menu:menuList)
                {
                    menu.setCategoryName(categoryMap.get(menu.getParent()));
                }

                for(MenuObject menu:menuList)
                {
                    if(finalMenuMap.get(menu.getCategoryName())==null)
                    {
                        List<MenuObject> newCategoryList = new ArrayList<>();
                        newCategoryList.add(menu);
                        finalMenuMap.put(menu.getCategoryName(),newCategoryList);
                    }else{
                        finalMenuMap.get(menu.getCategoryName()).add(menu);
                    }
                }

                session.setAttribute("menuList", finalMenuMap);
            }else{
                return JsonConverterUtil.loginInfoByJson(listResultDO.getErrorCode(),false);
            }*/

            return JsonConverterUtil.loginInfoByJson(authentication.getName(),true);
        }catch (UsernameNotFoundException e)
        {
            log.error("用户登录失败:error,{}", e.getMessage());
            return JsonConverterUtil.loginInfoByJson(e.getMessage(),false);
        }
        catch (AuthenticationException ex) {
            log.error("用户登录失败:error,{}", "登陆失败");
            return JsonConverterUtil.loginInfoByJson("密码不匹配",false);
        }
    }

    public HashMap<Integer,String> getCategoryMap() {
        List<Map<String, Object>> integerStringMap = categoryMapper.selectAllCategory();
        HashMap<Integer, String> categoryResultMap = new HashMap<>();
        for (Map<String, Object> map : integerStringMap) {
            Integer categoryId = null;
            String categoryName = null;
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                if (entry.getKey().equals("id")) {
                    categoryId = (Integer) entry.getValue();
                } else if (entry.getKey().equals("name")) {
                    categoryName = entry.getValue() + "";
                }
            }
            categoryResultMap.put(categoryId, categoryName);
        }
        return categoryResultMap;
    }

    public String buildMenuTree(int userId){
        //获取系统菜单
        ResultDO<List<MenuObject>> systemMenuList = resourcesServiceImpl.getSystemMenuList();
        //获取用户权限
        ResultDO<List<MenuObject>> accessResultDO = userRoleServiceImpl.selectMenusByUserID(userId);
        if(systemMenuList.isSuccess())
        {
            if(accessResultDO.isSuccess())
            {
                systemMenuList.getModule().addAll(accessResultDO.getModule());
            }
            MenuTree myMenuTree = new MenuTree(systemMenuList.getModule());
            return myMenuTree.buildTree();
        }else{
            return null;
        }
    }

}
